<?php

/**
 * Изображение
 *
 * @package    sf_sandbox
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfPropelFormTemplate.php 10377 2008-07-21 07:10:32Z dwhittle $
 */
class Type5Form extends BaseMaterialForm
{
  public function configure()
  {
  	
  		unset( 
  		$this['created_at'],  
  		$this['updated_at'],  
  		$this['user_id'], 
  		$this['see'], 
  		$this['click'], 
  		$this['country'],
  		$this['link'],
  		$this['custom_int1'],
  		$this['custom_int2'],
  		$this['custom_int3'],
  		$this['custom_text1'],
  		$this['custom_text2'],
  		$this['custom_text3'],
  		$this['custom_char1'],
  		$this['custom_char2'],
  		$this['stat'],
  		$this['city']);
  		
   		$c = new Criteria ( );	
		$c->addAnd ( FolderPeer::TREE_PARENT, 1, Criteria::NOT_EQUAL );
		$c->addAnd ( MaterialPeer::ID, 'tt' ); 	
  		
  		$this->setWidgets(array(
      'id'               => new sfWidgetFormInputHidden(),
  	  'parent_id'         => new sfWidgetParentMaterial(),	
      'title' =>  new sfWidgetFormInput(array(),array('size'=>50)),
  	  'type_id'           => new sfWidgetFormInputHidden(array(), array('value' =>'5', 'class'=>'test')),	 	 
  	  'photo_path' =>  new inputImageTag (  array (), array('mat_id'=>$this->object->getId(),'folder'=>'gallery') ), 
  	  'pub'      => new sfWidgetFormInputCheckbox(),
  	 
    ));
  		
    
         /////Ссылка на форум
		 if(sfConfig::get('app_use_link_forum')==true)
		 {
		 	$this->widgetSchema['custom_char3'] =  new sfWidgetFormInput(array(),array('size'=>'60'));
		 }
		 ////
		 
         /////Рейтинг
		 if(sfConfig::get('app_mat5_ratng')==true)
		 {
		 	$this->widgetSchema['rating'] =  new sfWidgetFormInput(array(),array('size'=>'6'));
		 }
		 ////		

         /////Короткое описание
		 if(sfConfig::get('app_mat5_short_desc')==true)
		 {
		 	$this->widgetSchema['short_content'] =  new sfWidgetFormTextareaNickEdit(array(),array('class'   =>  'material_short_content','style'=>'width:620px'));
		 }
		 ////		 
		 
		 /////Привязка к каталогу
		 if(sfConfig::get('app_mat5_folder')==true)
		 {
		 	$this->widgetSchema['mat2_folder_list'] =  new sfWidgetFormPropelChoiceMany ( array ('model' => 'Folder', 
  	                                                                  'multiple' => true,
  	                                                                  'expanded' => true,
  		                                                              'renderer_options' => array('formatter' =>array($this,'myFormatter')),
  	                                                                  'criteria' => $c ) );
		 }
		 ////
    
  		
      if(sfConfig::get('app_use_simple_region')==true)
    {
    $this->widgetSchema['region_id'] =  new sfWidgetFormPropelChoice(array('multiple' => false, 'expanded' => true, 'model' => 'Region', 'add_empty' => false));
    }
    
  		$this->widgetSchema->setLabels(array(  
		'title'    => 'Заголовок',  
  		'parent_id'   => 'Принадлежность',
		'photo_path'   => 'Рисунок',  
  		'content'   => 'Содержимое',
  		'pub'   => 'Опубликован',
  		'region_id'   => 'Регион',
  		'seo_keyword'   => 'SEO слова для поиска',
  		'mat2_folder_list'   => 'Каталоги',
  		'custom_char3'   => 'Ссылка на форум: ',
  		'rating'   => 'Рейтинг',
		'short_content' => 'Короткое описание',));
  		
    
     $this->validatorSchema['photo_path'] = new sfValidatorFile(array(
        'required'   => false,
        'path'       => sfConfig::get('sf_web_dir').'/uploads/material/gallery',
        'mime_types' => 'web_images',
        'max_size'   => 380000, // 360 kB
        'validated_file_class' => 'sfImageValidatedFile'
        ));
  		 $this->widgetSchema->setNameFormat('material[%s]');
  
  }
  
  
  	public function saveMat2FolderList($con = null) {
		if (! $this->isValid ()) {
			throw $this->getErrorSchema ();
		}
		
		if (! isset ( $this->widgetSchema ['mat2_folder_list'] )) {
			// somebody has unset this widget
			return;
		}
		
		if (is_null ( $con )) {
			$con = $this->getConnection ();
		}
		
		$c = new Criteria ( );
		$c->add ( Mat2FolderPeer::MATERIAL_ID, $this->object->getPrimaryKey () );
		Mat2FolderPeer::doDelete ( $c, $con );
		
		$values = $this->getValue ( 'mat2_folder_list' );
		if (is_array ( $values )) {
			
			foreach ( $values as $value ) {
				$obj = new Mat2Folder ( );
				$obj->setMaterialId ( $this->object->getPrimaryKey () );
				$obj->setFolderId ( $value );
				$obj->save ();
				
				$f = FolderPeer::retrieveByPK ( $value );
				
				////Добавляем счетчик
				FolderPeer::recount ( $f );
				
				if ($f->hasParent ()) {
					$par = $f->retrieveParent ();
					
					if (! in_array ( $par->getId (), $values )) {
						
						$this->saverec ( $par, $this->object->getPrimaryKey () );
						////Добавляем счетчик
						if ($par->hasParent ()) {
							$parr = $par->retrieveParent ();
							
							if (! in_array ( $parr->getId (), $values )) {
								//print_r($values).'-'.$parr->getId();
						         ////Добавляем счетчик
				                
								$this->saverec ( $parr, $this->object->getPrimaryKey () );
								if ($parr->hasParent ()) {
									$parrr = $parr->retrieveParent ();
									if (! in_array ( $parrr->getId (), $values )) {
										$this->saverec ( $parrr, $this->object->getPrimaryKey () );
						                ////Добавляем счетчик
				                       								
									}
								}
							
							}
						
						}
					}
				
				}
			
			}
		}
	}
	
	public function saverec($par, $mat_id) {
		
		//echo $par->getId().'-'.$mat_id;
		$c = new Criteria ( );
		$c->add ( Mat2FolderPeer::FOLDER_ID, $par->getId () );
		$c->addAnd ( Mat2FolderPeer::MATERIAL_ID, $mat_id );
		$cnt = Mat2FolderPeer::doCount ( $c );
		if ($cnt == 0) {
			$re = new Mat2Folder ( );
			$re->setMaterialId ( $mat_id );
			$re->setFolderId ( $par->getId () );
			$re->save ();
		}
	
	}
  
 function myFormatter($widget, $inputs)
  {
  	$str= '';
   $str = get_partial('checked_folders',array('arr'=>$this['mat2_folder_list']->getValue(),
                                                              'form'=>$this,
                                                              'scope_id'=>sfConfig::get('app_scope_gallery')
   )).get_component('zdFolder','show_folders',array('arr'=>$this['mat2_folder_list']->getValue(),
                                                    'folder_id'=>sfConfig::get('app_folder_gallery'),
                                                    'width_check'=>'yes'));
    //$str = '<b>Регионы</b>'.get_partial('checked_folders',array('form'=>$this,'scope_id'=>sfConfig::get('app_scope_region'))).get_component('zdFolder','show_folders',array('folder_id'=>sfConfig::get('app_folder_region'),'width_check'=>'yes'));
    return $str;
  }
  
  
public function save($con = null)
  {
    if (!$this->isValid())
    {
      throw $this->getErrorSchema();
    }

    if (is_null($con))
    {
      $con = $this->getConnection();
    }

    try
    {
      $con->beginTransaction();

      $this->doSave($con);

      $con->commit();
    }
    catch (Exception $e)
    {
      $con->rollBack();

      throw $e;
    }

    $o = $this->getObject();
    $c = new Criteria();
    $c->add(Material2MaterialPeer::FROM_ID,$o->getParentId());
    $c->addAnd(Material2MaterialPeer::TO_ID,$o->getId());
    $cnt = Material2MaterialPeer::doCount($c);
    

    
    if($cnt==0 and $o->getParentId()>0)
    {    
  	$f = new Material2Material();
  	$f->setFromId($o->getParentId());
  	$f->setToId($o->getId());
  	$f->save();
    }
    return $this->object;
  }
  
}
